package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Override
    public void delete(Long id) {
        noticeMapper.deleteNoticeAndEmployee(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Notice notice) {
        notice.setPubdate(new Date());
        notice.setIssuer(UserContext.getEmployee());
       noticeMapper.insert(notice);
    }

    @Override
    public Notice selectByPrimaryKey(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> selectAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public void update(Notice notice) {
        notice.setPubdate(new Date());
        notice.setIssuer(UserContext.getEmployee());
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Notice> notices = noticeMapper.queryForList(qo);
        return new PageInfo(notices);
    }

    @Override
    public PageInfo<Notice> selectIsRead(PageInfo pageInfo) {
        Employee employee = UserContext.getEmployee();
        List<Long> longs = noticeMapper.selectNoticeId(employee.getId());
        List list = pageInfo.getList();
        for (Object notice : list) {
            Notice notice1 = (Notice) notice;
            for (Long aLong : longs) {
                if (aLong == notice1.getId()){
                    notice1.setRead(true);
                }
            }
        }
        return pageInfo;
    }

    @Override
    public void show(Long id){
        Employee employee = UserContext.getEmployee();
        List<Long> longs = noticeMapper.selectNoticeId(employee.getId());
        for (Long aLong : longs) {
            if (aLong == id){
                return;
            }
        }
        noticeMapper.insertNew(id, employee.getId());
    }
}
